﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CML.Services.Interfaces;
using System.IO;

namespace CML.Services.Implementations
{
	public class FileService : IFileService
	{
		public void CopyDirectory(string sourceDirName, string destDirName, bool copySubDirs)
		{
			// Get the subdirectories for the specified directory.
			var dir = new DirectoryInfo(sourceDirName);
			var dirs = dir.GetDirectories();

			if (!dir.Exists)
			{
				throw new DirectoryNotFoundException(
					"Source directory does not exist or could not be found: "
					+ sourceDirName);
			}

			// If the destination directory doesn't exist, create it. 
			if (!Directory.Exists(destDirName))
			{
				Directory.CreateDirectory(destDirName);
			}

			// Get the files in the directory and copy them to the new location.
			FileInfo[] files = dir.GetFiles();
			foreach (FileInfo file in files)
			{
				string temppath = Path.Combine(destDirName, file.Name);
				file.CopyTo(temppath, false);
			}

			// If copying subdirectories, copy them and their contents to new location. 
			if (copySubDirs)
			{
				foreach (DirectoryInfo subdir in dirs)
				{
					string temppath = Path.Combine(destDirName, subdir.Name);
					CopyDirectory(subdir.FullName, temppath, copySubDirs);
				}
			}
		}

		public void WriteFile(string path, string content)
		{
			var dir = Path.GetDirectoryName(path);
			if (!Directory.Exists(dir))
				Directory.CreateDirectory(dir);
			using (var w = new StreamWriter(path, false))
			{
				w.Write(content);
			}
		}

		public void ClearFolder(string path)
		{
			DirectoryInfo dir = new DirectoryInfo(path);

			foreach (FileInfo fi in dir.GetFiles())
			{
				fi.Delete();
			}

			foreach (DirectoryInfo di in dir.GetDirectories())
			{
				ClearFolder(di.FullName);
				di.Delete();
			}
		}

		public void CreateOrClearFolder(string path)
		{
			if (Directory.Exists(path))
				ClearFolder(path);
			else
				Directory.CreateDirectory(path);
		}

		public string GetFileContent(string path)
		{			
			using (var r = new StreamReader(path))
			{
				var s = r.ReadToEnd();
				return s;
			}
		}

	}
}
